<template>
  <list-frame :show-selection="true" :show-advance-query="true" :total="queryForm.total" :table-data="orderList"
    :columns="columns" @page-changed="onPageChanged" @size-changed="onSizeChanged" @query="onQuery"
    @row-selected="onRowSelected" :operation-width="200">
    <template #base>
      <el-select clearable v-model="queryForm.orderStatus" placeholder="订单状态" style="width: 140px;">
        <el-option v-for="item in OrderStatusList" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-select clearable v-model="queryForm.customerCode" placeholder="客户" style="width: 140px;margin-left: 4px;">
        <el-option v-for="item in customerList" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-select clearable v-model="queryForm.productCode" placeholder="产品" style="width: 140px;margin-left: 4px;">
        <el-option v-for="item in productList" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-input v-model="queryForm.contactor" placeholder="联系人" clearable
        style="width: 140px;margin-left: 4px;"></el-input>
      <el-input v-model="queryForm.telephone" placeholder="联系电话" clearable
        style="width: 140px;margin-left: 4px;"></el-input>
      <el-input v-model="queryForm.productSn" clearable placeholder="SN"
        style="width: 140px;margin-left: 4px;"></el-input>
      <el-input v-model="queryForm.receiveNumber" clearable placeholder="接收快递单号"
        style="width: 140px;margin-left: 4px;"></el-input>
    </template>
    <template #advance>
      <el-form inline :label-width="100" label-suffix=":">
        <el-form-item class="form-item" label="订单编号">
          <el-input v-model="queryForm.orderNumber"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="订单状态">
          <el-select clearable v-model="queryForm.orderStatus" placeholder="选择订单状态">
            <el-option v-for="item in OrderStatusList" :key="item.code" :label="item.name"
              :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="客户">
          <el-select clearable v-model="queryForm.customerCode" placeholder="选择客户">
            <el-option v-for="item in customerList" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="产品">
          <el-select clearable v-model="queryForm.productCode" placeholder="选择产品">
            <el-option v-for="item in productList" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="联系人">
          <el-input v-model="queryForm.contactor"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="电话">
          <el-input v-model="queryForm.telephone"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="SN">
          <el-input v-model="queryForm.productSn"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="接收快递单号">
          <el-input v-model="queryForm.receiveNumber"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="返回快递单号">
          <el-input v-model="queryForm.returnNumber"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="付款状态">
          <el-select clearable v-model="queryForm.payState">
            <el-option v-for="item in ['是', '否']" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="工程师">
          <el-select clearable v-model="queryForm.createUserId">
            <el-option v-for="item in userList" :key="item.guid" :label="item.realName" :value="item.guid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item-line" label="接收快递日期">
          <zw-date-range-picker seperator="-" v-model="receiveDate"></zw-date-range-picker>
        </el-form-item>
        <el-form-item class="form-item-line" label="工单创建日期">
          <zw-date-range-picker seperator="-" v-model="orderCreateDate"></zw-date-range-picker>
        </el-form-item>
        <el-form-item class="form-item-line" label="维修完成日期">
          <zw-date-range-picker seperator="-" v-model="orderCompleteDate"></zw-date-range-picker>
        </el-form-item>
      </el-form>
    </template>
    <template #append>
      <el-button type="primary" size="small" @click="reload" :icon="Refresh" title="重置"></el-button>
      <el-button type="primary" size="small" color="#626aef" @click="onCreate" :icon="CirclePlusFilled"
        title="添加工单"></el-button>
      <el-button type="primary" size="small" color="#219b97" :icon="UploadFilled" @click="onImportShow"
        title="上传"></el-button>
      <el-button type="primary" size="small" color="#219b97" :icon="Bottom" @click="onExport" title="导出"></el-button>
    </template>
    <template #dialog>
      <zw-importer action="/api/shipping/import" :visible="importVisible" @close="importVisible = false"
        @import="onImport"></zw-importer>
      <zw-file-downloader :visible="downloaderVisible" :file-ids="fileIds" @close="downloaderVisible = false"
        @downloaded="onDownloaded"></zw-file-downloader>
      <zw-file-downloader :visible="reportDownloaderVisible" :file-ids="reportIds"
        @close="reportDownloaderVisible = false" @downloaded="onReportDownloaded"></zw-file-downloader>
    </template>
    <template #operations="row">
      <el-button link type="primary" size="default" @click="onDetail(row)">详情</el-button>
      <el-button link type="primary" size="default" @click="onGenerateReport(row)">检测报告单</el-button>
    </template>
  </list-frame>
</template>
<script lang="ts" setup>
import type { ColumnType } from '@/components/types';
import ZwImporter from '@/components/Form/ZwImporter.vue';
import ListFrame from '@/components/ListFrame/ListFrame.vue';
import ZwFileDownloader from '@/components/Form/ZwFileDownloader.vue';
import ApiTree from '@/server/api-tree';
import { onMounted, ref, watch } from 'vue';
import { DictTypeEnum, type DictVO } from '@/server/dict/types';
import ZwDateRangePicker from '@/components/Form/ZwDateRangePicker.vue';
import emits, { EventEnum } from '@/plugins/emits';
import { type OrderViewDTO, type QueryOrderVO, OrderStatusList } from '@/server/afterSale/types';
import { type UserVO } from '@/server/user/types';
import StrUitl from '@/plugins/str';
import { ElMessage } from 'element-plus';
import ElConfirm from '@/components/ElConfirm';
import WinUtil, { WinNameRecord } from '@/plugins/window';
import { UploadFilled, Bottom, Refresh, CirclePlusFilled } from "@element-plus/icons-vue"
/** 表格属性 */
const columns = ref<ColumnType[]>([
  { prop: "orderNumber", colName: "维修单号", width: 160 },
  { prop: "orderStatusName", colName: "维修状态", width: 120 },
  { prop: "customerName", colName: "客户名称", width: 120 },
  { prop: "contactor", colName: "联系人", width: 100 },
  { prop: "telephone", colName: "电话", width: 120 },
  { prop: "productCount", colName: "设备数量", width: 80 },
  { prop: "checkEngineer", colName: "检测工程师", width: 120 },
  { prop: "repairEngineer", colName: "维修工程师", width: 120 },
  { prop: "cuser", colName: "创建人", width: 120 },
  { prop: "ctime", colName: "创建时间", width: 160 },
]);

/** 查询工单列表 */
const queryForm = ref<QueryOrderVO>({
  orderNumber: "",
  orderStatus: "",
  customerCode: "",
  productCode: "",
  telephone: "",
  contactor: "",
  productSn: "",
  receiveNumber: "",
  returnNumber: "",
  payState: "",
  receiveDateStart: "",
  receiveDateEnd: "",
  orderCreateDateStart: "",
  orderCreateDateEnd: "",
  orderCompleteDateStart: "",
  orderCompleteDateEnd: "",
  createUserId: "",
  pageNo: 1,
  pageSize: 30,
  total: 0
});
// 用来处理日期的参数
const receiveDate = ref<string[]>([]);
watch(() => receiveDate.value, () => {
  if (receiveDate.value.length === 2) {
    queryForm.value.receiveDateStart = receiveDate.value[0];
    queryForm.value.receiveDateEnd = receiveDate.value[1]
  } else {
    queryForm.value.receiveDateStart = "";
    queryForm.value.receiveDateEnd = ""
  }
})
const orderCreateDate = ref<string[]>([]);
watch(() => orderCreateDate.value, () => {
  if (orderCreateDate.value.length === 2) {
    queryForm.value.orderCreateDateStart = orderCreateDate.value[0];
    queryForm.value.orderCreateDateEnd = orderCreateDate.value[1]
  } else {
    queryForm.value.orderCreateDateStart = "";
    queryForm.value.orderCreateDateEnd = ""
  }
})

const orderCompleteDate = ref<string[]>([]);
watch(() => orderCompleteDate.value, () => {
  if (orderCompleteDate.value.length === 2) {
    queryForm.value.orderCompleteDateStart = orderCompleteDate.value[0];
    queryForm.value.orderCompleteDateEnd = orderCompleteDate.value[1]
  } else {
    queryForm.value.orderCompleteDateStart = "";
    queryForm.value.orderCompleteDateEnd = ""
  }
})
const initForm = () => {
  queryForm.value = {
    orderNumber: "",
    orderStatus: "",
    customerCode: "",
    productCode: "",
    telephone: "",
    contactor: "",
    productSn: "",
    receiveNumber: "",
    returnNumber: "",
    payState: "",
    receiveDateStart: "",
    receiveDateEnd: "",
    orderCreateDateStart: "",
    orderCreateDateEnd: "",
    orderCompleteDateStart: "",
    orderCompleteDateEnd: "",
    createUserId: "",
    pageNo: 1,
    pageSize: queryForm.value.pageSize,
    total: 0
  }
}
const orderList = ref<OrderViewDTO[]>([])
const reload = () => {
  initForm();
  getOrderList();
}
const getOrderList = async () => {
  const { success, data, totalCount } = await ApiTree.afterSaleOrder.page(queryForm.value);
  if (success) {
    orderList.value = data.map(x => {
      //x.orderStatus = OrderStatusList.find(o => o.code === x.orderStatus)?.name || "";
      x.checkEngineer = StrUitl.trimStart(x.checkEngineer, ',');
      x.repairEngineer = StrUitl.trimStart(x.repairEngineer, ',');
      return x;
    });
    queryForm.value.total = totalCount;
  }
}
const onPageChanged = (pageNo: number) => {
  queryForm.value.pageNo = pageNo;
  getOrderList();
}
const onSizeChanged = (pageSize: number) => {
  queryForm.value.pageSize = pageSize;
  getOrderList();
}
const onQuery = () => {
  queryForm.value.pageNo = 1;
  getOrderList();
}
/** 获取客户列表 */
const customerList = ref<DictVO[]>([])
const getCustomerList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.CUSTOMER, true);
  if (success) {
    customerList.value = data;
  }
}
/** 获取产品列表 */
const productList = ref<DictVO[]>([])
const getProductList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.PRODUCT, true);
  if (success) {
    productList.value = data;
  }
}
/** 获取用户列表 */
const userList = ref<UserVO[]>([])
const getUserList = async () => {
  const { success, data } = await ApiTree.user.page({ userName: "", realName: "", role: "", pageNo: 1, pageSize: 999, total: 0 });
  if (success) {
    userList.value = data;
  }
}
const onCreate = () => {
  WinUtil.open("/afterSale/order/create", WinNameRecord.ORDER_CREATE);
}
const onDetail = (row: { value: OrderViewDTO }) => {
  WinUtil.open("/afterSale/order/detail?guid=" + row.value.guid, WinNameRecord.ORDER_DETAIL, row.value.guid);
}
/** 生成检测报告单 */
const reportDownloaderVisible = ref(false);
const reportIds = ref<string[]>([])
const onGenerateReport = (row: { value: OrderViewDTO }) => {
  const data = row.value as OrderViewDTO;
  ElConfirm(`确定要生成工单【${data.orderNumber}】的检测报告单吗？`).then(async () => {
    const { success, data: fileId } = await ApiTree.afterSaleOrder.generateReport(data.guid);
    if (success) {
      reportIds.value = [fileId];
      reportDownloaderVisible.value = true;
    }
  }).catch();
}
const onReportDownloaded = () => {
  reportDownloaderVisible.value = false;
  reportIds.value = []
}
/** 导出数据 */
const selectedRows = ref<OrderViewDTO[]>([])

const onRowSelected = (value: OrderViewDTO[]) => {
  selectedRows.value = value;
}
const downloaderVisible = ref(false)
const fileIds = ref<string[]>([])
const onExport = () => {
  ElConfirm(`确定要导出数据吗？未设置检索条件将导出全部数据。`).then(async () => {
    const { success, data } = await ApiTree.afterSaleOrder.export(queryForm.value, selectedRows.value.map(x => x.guid));
    if (success && data) {
      fileIds.value = [data]
      downloaderVisible.value = true;
    }
  }).catch();
}
const onDownloaded = () => {
  fileIds.value = [];
  downloaderVisible.value = false;
}
/** 导入数据 */
const importVisible = ref(false);
const onImportShow = () => {
  importVisible.value = true;
}
const onImport = async (fileId: string[], callback: () => void) => {
  const { success, msg } = await ApiTree.afterSaleOrder.importData(fileId[0]);
  if (success) {
    ElMessage.success(msg);
    reload();
  } else {
    ElMessage.error(msg)
  }
  importVisible.value = false;
  callback();
}
onMounted(() => {
  getCustomerList();
  getProductList();
  getUserList();
  reload();
  emits.on(EventEnum.TABLE_RELOAD, reload);
})
</script>
<style lang="scss" scope></style>
